package com.ganzalang.gmall.minio.sample;


import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class FileUploader {

    private final static String BUCKET_NAME =  "asia";
    private final static String FILE_NAME = "D:\\Google Download\\博客图片\\yunying.png";
    private final static String OBJECT_NAME = "yunying.png";


    public static void main(String[] args)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {

            MinIOProperties minIOProperties = getMinIOProperties();


            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minIOProperties.getEndpoint())
                            .credentials(minIOProperties.getAccessKey(), minIOProperties.getSecretKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
            } else {
                System.out.println("Bucket '" + BUCKET_NAME + "' already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(BUCKET_NAME)
//                            .object("asiaphotos-2015.zip")
                            .object(OBJECT_NAME)
//                            .filename("/home/user/Photos/asiaphotos.zip")
                            .filename(FILE_NAME)
                            .build());
            System.out.println(
                    "'" + FILE_NAME + "' is successfully uploaded as "
                            + "object '" + OBJECT_NAME + "' to bucket '" + BUCKET_NAME + "'.");
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
    }

    /**
     * 构造MinIO Server的配置
     * @return
     */
    private static MinIOProperties getMinIOProperties(){
        MinIOProperties properties = new MinIOProperties();
        properties.setEndpoint("http://192.168.163.128:9001");
        properties.setAccessKey("kLCCny4gsGsNYrMN");
        properties.setSecretKey("2eXuvFDbf28Uk8FAf2LMXTj0rRTU43tt");
        return properties;
    }
}
